import { Component } from '@angular/core';

@Component({
  selector: 'find-slider',
  templateUrl: './slider.component.html',
  styleUrls: ['./slider.component.scss']
})
export class SliderComponent {
  ngOnInit(){
    // constructor 生命周期处于页面DOM没有被渲染的时候，所以SliderShow不能在这里写
    // 新增一个OnInit的生命周期，写在ngOnInit函数内
    this.initSliderShow();
  }
  initSliderShow(){
    const slider = new Slider('slider');
    setInterval(() => {
        slider.slideNext();
    }, 2000);
  }
}
//轮播图 类定义
class Slider {
  container:HTMLElement|null
  items:any | NodeListOf<Element> | null = null
  constructor(id:string) {
      this.container = document.getElementById(id);
      if(this.container){
        this.items = this.container.querySelectorAll('.slider-list_item, .slider-list_item-selected');
      }
      // 获取指定的所有元素，返回一个类数组
  }
  //获取选中的图片元素
  getSelectedItem() {
    if(this.container){
      let selected = this.container.querySelector('.slider-list_item-selected');
      return selected
    }
    return null
  }
  //获取选中图片的索引值，返回其在items数组中的位置
  getSelectedItemIndex() {
      return Array.from(this.items).indexOf(this.getSelectedItem());
      //Array.from()将类数组转换成真正的数组 indexOf()返回指定的字符首次出现的位置     就是获取索引
  }
  // 跳转到指定索引的图片
  slideTo(idx:string) {
      const selected = this.getSelectedItem();
      if (selected) {
          selected.className = 'slider-list_item';
      }
      const item = this.items[idx];
      if (item) {
          item.className = 'slider-list_item-selected';
      }
  }
  // 跳转到下一索引的图片，将下一张图片标记为选中状态
  slideNext() {
      const currentIdx = this.getSelectedItemIndex();
      const nextIdx = (currentIdx + 1) % this.items.length;
      this.slideTo(String(nextIdx));
  }
  // 跳转到上一索引的图片，将上一张图片标记为选中状态
  slidePrevious() {
      const currentIdx = this.getSelectedItemIndex();
      const previousIdx = (this.items.length + currentIdx - 1)
          % this.items.length;
      this.slideTo(String(previousIdx));
  }
 }
